class Request {
  defaults = {
    baseURL: "",
    url: "",
    data: null,
    method: "GET",
    header: {
      "Content-type": "application/json"
    },
    timeout: 60000
  }

  // 拦截器
  interceptors = {
    // 请求拦截器
    request: (config) => config,
    // 响应拦截器
    response: (response) => response
  }

  constructor(params = {}) {
    this.defaults = Object.assign({}, this.defaults, params)
  }

  request(options) {
    options.url = this.defaults.baseURL + options.url
    options = {
      ...this.defaults,
      ...options
    }

    // 请求发送前调用请求拦截器
    options = this.interceptors.request(options)

    return new Promise((resolve, reject) => {
      wx.request({
        ...options,

        success: (res) => {
          // 响应拦截器
          res = this.interceptors.response({
            ...res,
            isSuccess: true
          })
          resolve(res)
        },
        fail: (err) => {
          err = this.interceptors.response({
            ...err,
            isSuccess: false
          })
          reject(err)
        },
      })
    })
  }

  get(url, data = {}, config = {}) {
    const options = Object.assign({
      url,
      data,
      method: "GET"
    }, config)
    return this.request(options)
  }

  post(url, data = {}, config = {}) {
    const options = Object.assign({
      url,
      data,
      method: "POST"
    }, config)
    return this.request(options)
  }
}

export default Request